/**
 * @version 3.0.5
 * @Author lu-ch
 * @Email webwork.s@qq.com
 * 文档: https://www.quanzhan.co/luch-request/
 * github: https://github.com/lei-mu/luch-request
 * DCloud: http://ext.dcloud.net.cn/plugin?id=392
 * HBuilderX: beat-3.0.4 alpha-3.0.4
 */

import Request from 'luch-request'
import storage from './storage'
import { useUserStore } from '@/store/user';

let isRefreshing = false;
const requestQueue = [];

const http = new Request()
http.setConfig((config) => { /* 设置全局配置 */
  config.baseURL = 'http://zzzccc.natapp1.cc'
  config.header = {
    ...config.header,
  }
  return config
})

http.interceptors.request.use((config) => { /* 请求之前拦截器。可以使用async await 做异步操作 */
  config.header = {
    ...config.header,
    'Authorization': 'Bearer ' + storage().get('ACCESS_TOKEN')
  }
	// 演示custom 用处
	// if (config.custom.auth) {
	//   config.header.ACCESS_TOKEN = 'ACCESS_TOKEN'
	// }
	if (config?.custom?.loading) {
	 uni.showLoading({
		 title: '加载中...'
	 })
	}
  /*
 if (!ACCESS_TOKEN) { // 如果ACCESS_TOKEN不存在，return Promise.reject(config) 会取消本次请求
   return Promise.reject(config)
 }
 */
  return config
}, (config) => {
  return Promise.reject(config)
})


http.interceptors.response.use(async (response) => { /* 请求之后拦截器。可以使用async await 做异步操作  */
	const { code } = response.data
	const config = response.config
	if (config?.custom?.loading) {
		uni.hideLoading()
	}
	switch (code) {
		case 400:
		case 500:
		case 502:
			console.log(config)
			uni.showToast({
				title: '请求失败',
				icon: 'none',
				success: () => {
					uni.hideLoading()
				}
			})
			return Promise.reject(response.data)
	}
	return response.data
}, async (response) => { // 请求错误做点什么。可以使用async await 做异步操作
	const { login, clearUserInfo } = useUserStore()
	const { statusCode, config } = response
	switch (statusCode) {
		case 401:
			clearUserInfo()
			
			// 创建重试 Promise（加入队列）
			const retryPromise = new Promise((resolve, reject) => {
			  requestQueue.push({ resolve, reject, config: config || {} });
			});
			
			if (!isRefreshing) {
				isRefreshing = true;
				try {
					await login()
					
					// 复制当前队列并清空（隔离重试期间的新请求）
					const queueSnapshot = [...requestQueue];
					requestQueue.length = 0;
					
					// 重试所有历史请求
					const retryTasks = queueSnapshot.map(({ resolve, reject, config }) =>
					  http.middleware(config).then(resolve).catch(reject),
					);
					
					// 等待所有重试完成
					await Promise.allSettled(retryTasks);
				} catch (refreshError) {
					requestQueue.forEach((item) => item.reject(refreshError));
					requestQueue.length = 0;
					return Promise.reject(refreshError);
				} finally {
					isRefreshing = false;
				}
			}
			return retryPromise;
	}
	return Promise.reject(response)
})

export {
  http
}
